package Servlet;

import Bean.User;
import Service.UserService;
import Utils.UUIDUtils;
import Utils.UploadFileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2025-03-16
 * Time: 12:36
 */
//修改用户信息 --- 管理员端
@WebServlet("/UserUpdateServlet")
@MultipartConfig(
        maxFileSize = 5 * 1024 * 1024,  // 限制文件大小5MB
        fileSizeThreshold = 1024 * 1024  // 内存缓冲1MB
)
public class UserUpdateServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf8");
        User user = new User();
        user.setUserId(req.getParameter("userId"));
        user.setName(req.getParameter("name"));
        System.out.println("[UserUpdateServlet] 捕获到的 username 为 : " + user.getName());
        user.setPhone(req.getParameter("phone"));
        user.setPassword(req.getParameter("password"));
        user.setIdentityCard(req.getParameter("identityCard"));
        //处理头像
        Part filePart = req.getPart("uimage");
        UploadFileUtil uploadUtil = new UploadFileUtil();

        //设置保存路径
        String uploadPath = "D:\\upload\\avatars";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs(); // 创建多级目录
        }

        uploadUtil.setPath(uploadPath);
        uploadUtil.setPart(filePart);
        String originalFilename = uploadUtil.getFilename();
        user.setUimage("/avatars/" + originalFilename);
        System.out.println("[UserUpdateServlet] 修改过后的用户数据为 : " + user.toString());
        //更新用户数据
        boolean ok = false;

        if(uploadUtil.saveFile(originalFilename) == 1) {
            //提交注册申请
            ok = userService.update(user);
        }
        if(!ok) {
            req.setAttribute("status", "error");
            req.setAttribute("message", "修改失败");
            req.setAttribute("redirectUrl", "UserList?pageNo=1");
            req.setAttribute("waitSeconds", 2);
            req.getRequestDispatcher("skip.jsp").forward(req,resp);
        }
        req.getRequestDispatcher("UserList?pageNo=1").forward(req,resp);
    }
}
